package com.taxi.controller;

import com.taxi.service.OrderInfoService;
import com.taxi.constant.IdentityConstant;
import com.taxi.dto.OrderDetailInfo;
import com.taxi.dto.OrderInfo;
import com.taxi.dto.TokenResult;
import com.taxi.request.OrderRequest;
import com.taxi.result.Result;
import com.taxi.util.JwtUtils;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;

/**
 * @Author: aniu
 * @Date: 2023/10/3
 * @ClassName: OrderController
 * @Description: Write class functionality and purpose here.
 * @Version: 1.0
 */
@RestController
@RequestMapping("/order")
public class OrderInfoController {
    @Autowired
    private OrderInfoService orderInfoService;

    @ApiOperation("/创建订单/下单")
    @PostMapping("/add")
    public Result add(@Validated @RequestBody OrderRequest orderRequest,HttpServletRequest request){
        String phone = getPhone(request);
        orderRequest.setPassengerPhone(phone);
        return orderInfoService.add(orderRequest);
    }

    @ApiOperation("乘客取消订单")
    @PostMapping("/cancel")
    public Result cancel(Long orderId){
        return orderInfoService.cancel(orderId);
    }


    @GetMapping("/current")
    public Result<OrderInfo> currentOrder(HttpServletRequest httpServletRequest){
        String phone = getPhone(httpServletRequest);
        return orderInfoService.currentOrder(phone,IdentityConstant.PASSENGER_IDENTITY);
    }

    @GetMapping("/current-order-detail")
    public Result<OrderDetailInfo> currentOrderDetail(@RequestParam Long orderId){
        return orderInfoService.currentOrderDetail(orderId);
    }

    @GetMapping("/get-all-orders")
    public Result<ArrayList<OrderInfo>> getAllOrders(HttpServletRequest httpServletRequest){
        String phone = getPhone(httpServletRequest);
        return orderInfoService.getAllOrders(phone,IdentityConstant.PASSENGER_IDENTITY);
    }

    /**
     * 获取手机号
     * @param httpServletRequest
     * @return
     */
    public String getPhone(HttpServletRequest httpServletRequest){
        String authorization = httpServletRequest.getHeader("Authorization");
        TokenResult tokenResult = JwtUtils.parseToken(authorization);
        String identity = tokenResult.getIdentity();
        if (!identity.equals(IdentityConstant.PASSENGER_IDENTITY)){
            return null;
        }
        return tokenResult.getPhone();
    }
}
